package com.azthink.chapter422.aspect;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Modifier;

@Component
@Aspect
public class HttpAspect {

    @Pointcut("execution(public * com.azthink.chapter422.controller.*.*(..))")
    public void cut(){}

    @Before("cut()")
    public void doBefore(JoinPoint joinPoint){
        //记录请求的url


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        System.out.println("url = " + request.getRequestURI());
        //method
        System.out.println("method = "+ request.getMethod());
        //ip
        System.out.println("ip = "+request.getRemoteAddr());



        Signature signature = joinPoint.getSignature();
        System.out.println("目标方法名为:" + signature.getName());
        System.out.println("目标方法所属类的简单类名:" +  signature.getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + signature.getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));

        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i+1) + "个参数为:" + args[i]);
        }


        System.out.println("执行前");
    }

    @After("cut()")
    public void doAfter(){
        System.out.println("执行后");
    }

    @AfterReturning(returning = "obj", pointcut = "cut()")
    public void doAfterReturning(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("response="+ objectMapper.writeValueAsString(obj));
    }


}